package http

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/liyaozong/mengo/common/di"
	commonDTO "github.com/liyaozong/mengo/contracts/dtos/common"
	"github.com/liyaozong/mengo/contracts/dtos/requests"
	"github.com/liyaozong/mengo/core/base/container"
	"github.com/liyaozong/mengo/core/device/application"
)

type DeviceController struct {
	dic *di.Container
}

// NewDeviceController creates and initializes an DeviceController
func NewDeviceController(dic *di.Container) *DeviceController {
	return &DeviceController{
		dic: dic,
	}
}

func (dc *DeviceController) AddDevice(ctx *gin.Context) {
	lc := container.LoggingClientFrom(dc.dic.Get)

	var reqDTOs []requests.AddDeviceRequest
	if err := ctx.Bind(&reqDTOs); err != nil {
		ctx.JSON(http.StatusBadRequest, err.Error())
		return
	}

	var addResponses []interface{}
	for i, d := range reqDTOs {
		var response interface{}
		reqId := reqDTOs[i].RequestId
		newId, err := application.AddDevice(d.Device, ctx, dc.dic)
		if err != nil {
			lc.Debug(err.DebugMessages())
			response = commonDTO.NewBaseResponse(
				reqId,
				err.Message(),
				err.Code())
		} else {
			response = commonDTO.NewBaseWithIdResponse(
				reqId,
				"",
				http.StatusCreated,
				newId)
		}
		addResponses = append(addResponses, response)
	}

	ctx.JSON(http.StatusMultiStatus, addResponses)
}
